<template>
  <page-container title="OTA列表" class="container">
    <!-- 操作栏 -->
    <div class="action-container">
      <div class="update-buttons">
        <!--更新部分设备按钮-->
        <el-button
          type="primary"
          @click="showOnlineDevices"
          style="margin-right: 10px"
        >
          选择更新在线设备
        </el-button>
        <!--更新离线设备按钮-->
        <el-button
          type="warning"
          @click="showOfflineDevices"
          style="margin-right: 10px"
        >
          选择更新离线设备
        </el-button>
      </div>
      <!--选择产品型号-->
      <el-select
        v-model="selectedProductType"
        placeholder="请选择产品型号"
        clearable
        filterable
        @change="handleTypeChange"
        style="width: 200px; margin-right: 20px"
      >
        <el-option
          v-for="item in productTypes"
          :key="item"
          :label="item"
          :value="item"
        />
      </el-select>
      <!--更新全部ota按钮-->
      <el-button
        type="primary"
        @click="showGlobalUpdateDialog"
        :loading="updateLoading"
      >
        一键更新全部在线设备
      </el-button>
    </div>
    <!--ota表格-->
    <el-table
      v-loading="loading"
      :data="originalData"
      style="width: 100%"
      height="550px"
    >
      <el-table-column type="index" label="序号" width="100" align="center" />
      <el-table-column label="OTA文件" align="center">
        <template #default="{ row }">
          {{ row.otaFileName || '未上传文件' }}
        </template>
      </el-table-column>

      <el-table-column label="ota版本号" align="center" width="120">
        <template #default="{ row }"> v{{ row.softwareVersion }} </template>
      </el-table-column>
      <el-table-column label="硬件版本号" align="center" width="120">
        <template #default="{ row }"> v{{ row.hardwareVersion }} </template>
      </el-table-column>
      <el-table-column label="记录创建时间" align="center" width="180">
        <template #default="{ row }">
          {{ row.createAt ? formatTime(row.createAt) : '无记录' }}
        </template>
      </el-table-column>
      <el-table-column
        prop="productType"
        label="产品型号"
        align="center"
        width="150"
      />
      <el-table-column label="操作" align="center" width="300">
        <template #default="{ row }">
          <el-button type="danger" @click="handleDelete(row)">删除</el-button>
          <el-button type="primary" @click="handleEdit(row)">修改</el-button>
        </template>
      </el-table-column>

      <template #empty>
        <el-empty :description="emptyDescription" />
      </template>
    </el-table>

    <!--删除ota固件包-->
    <el-dialog v-model="DeleteDialogVisible" title="删除OTA固件包" width="500">
      <span>是否要删除该OTA固件包？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="DeleteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmDelete"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>

    <!--修改ota参数-->
    <el-dialog v-model="EditDialogVisible" title="修改OTA固件包" width="600">
      <el-form :model="form">
        <el-form-item label="产品型号" :label-width="250">
          <el-input v-model="form.productType" autocomplete="off" clearable />
        </el-form-item>
        <el-form-item label="固件版本号（格式：xx.xx.xx）" :label-width="250">
          <el-input
            v-model="form.softwareVersion"
            autocomplete="off"
            @input="(val) => (form.softwareVersion = filterVersionInput(val))"
            clearable
          >
            <template #suffix>
              <span v-if="form.softwareVersion && !isValidSoftwareVersion"
                >⚠</span
              >
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="硬件版本号（格式：xx.xx）" :label-width="250">
          <el-input
            v-model="form.hardwareVersion"
            autocomplete="off"
            @input="(val) => (form.hardwareVersion = filterVersionInput(val))"
            clearable
          >
            <template #suffix>
              <span v-if="form.hardwareVersion && !isValidHardwareVersion"
                >⚠</span
              >
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="OTA固件包" :label-width="250">
          <el-upload
            drag
            ref="uploadRef"
            class="upload-demo"
            action="#"
            :limit="1"
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :file-list="fileList"
            :show-file-list="true"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              拖拽固件包至此或<em>点击选择文件</em>
              <div class="el-upload__tip">最大支持500MB</div>
              <span v-if="fileSizeWarning" class="warning-text"
                >(文件过大!)</span
              >
            </div>
            <template #file="{ file }">
              <div class="file-preview">
                <el-icon><document /></el-icon>
                <span>{{ file.name }} ({{ formatFileSize(file.size) }})</span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="EditDialogVisible = false"> 取消 </el-button>
          <el-button
            type="primary"
            @click="confirmEdit"
            :disabled="fileSizeWarning"
          >
            确认修改
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 离线设备弹窗 -->
    <el-dialog
      v-model="OfflineDialogVisible"
      title="选择更新离线设备"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-checkbox-group v-model="selectedOfflineDevices">
        <div
          v-loading="deviceLoading"
          style="max-height: 400px; overflow-y: auto"
        >
          <div
            v-for="device in offlineDeviceList"
            :key="device.id"
            style="padding: 8px 0; border-bottom: 1px solid #eee"
          >
            <el-checkbox :label="device.id">
              <span style="margin-left: 8px">{{ device.equipmentNo }}</span>
              <el-tag
                size="small"
                effect="plain"
                type="info"
                style="margin-left: 10px"
              >
                {{ device.onlineState }}
              </el-tag>
            </el-checkbox>
          </div>
          <el-empty
            v-if="!offlineDeviceList.length"
            description="暂无离线设备"
          />
        </div>
      </el-checkbox-group>
      <template #footer>
        <el-button
          @click="
            OfflineDialogVisible = false;
            selectedOfflineDevices = []
          "
          >取消</el-button
        >
        <el-button
          type="primary"
          @click="handleOfflineUpgrade"
          :loading="updateLoading"
        >
          确认离线升级（{{ selectedOfflineDevices.length }}台）
        </el-button>
      </template>
    </el-dialog>

    <!-- 在线设备弹窗 -->
    <el-dialog
      v-model="OnlineDialogVisible"
      title="选择更新在线设备"
      width="700px"
      :close-on-click-modal="false"
    >
      <!-- 版本选择区域 -->
      <div class="version-selection">
        <div class="version-item">
          <span class="version-label">固件版本：</span>
          <el-select
            v-model="selectedVersion"
            placeholder="请选择固件版本"
            clearable
          >
            <el-option
              v-for="option in versionOptions"
              :key="option.key"
              :label="option.display"
              :value="option.value"
            />
          </el-select>
        </div>
      </div>

      <!--设备列表-->
      <el-checkbox-group v-model="selectedOnlineDevices">
        <div
          v-loading="deviceLoading"
          style="max-height: 400px; overflow-y: auto"
        >
          <div
            v-for="device in onlineDeviceList"
            :key="device.id"
            style="padding: 8px 0; border-bottom: 1px solid #eee"
          >
            <el-checkbox :label="device.equipmentNo">
              <span style="margin-left: 8px">{{ device.equipmentNo }}</span>
              <el-tag
                size="small"
                effect="plain"
                type="success"
                style="margin-left: 10px"
              >
                {{ device.onlineState }}
              </el-tag>
            </el-checkbox>
          </div>
          <el-empty
            v-if="!deviceLoading && onlineDeviceList.length === 0"
            description="暂无在线设备"
          />
        </div>
      </el-checkbox-group>
      <template #footer>
        <el-button
          @click="
            OnlineDialogVisible = false;
            selectedOnlineDevices = []
          "
          >取消</el-button
        >
        <el-button
          type="primary"
          @click="handleOnlineUpgrade"
          :loading="updateLoading"
          :disabled="!selectedVersion"
        >
          确认在线升级（{{ selectedOnlineDevices.length }}台）
        </el-button>
      </template>
    </el-dialog>

    <!-- 一键更新弹窗 -->
    <el-dialog
      v-model="globalUpdateDialogVisible"
      title="选择更新固件版本"
      width="500px"
      :close-on-click-modal="false"
    >
      <!-- 版本选择区域 -->
      <div class="version-selection">
        <div class="version-item">
          <span class="version-label">固件版本：</span>
          <el-select
            v-model="globalSelectedVersion"
            placeholder="请选择固件版本"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="option in versionOptions"
              :key="option.key"
              :label="option.display"
              :value="option.value"
            />
          </el-select>
        </div>
      </div>

      <template #footer>
        <el-button @click="globalUpdateDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="handleGlobalUpdate"
          :loading="updateLoading"
          :disabled="!globalSelectedVersion"
        >
          确认更新
        </el-button>
      </template>
    </el-dialog>
  </page-container>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import {
  getOTAlist,
  updateAllOTA,
  getProductType,
  remoteGetEquipmentNumList,
  DeleteOTA,
  EditOTA,
  updateOnlineOTA,
  updateOfflineOTA
} from '@/api/clothrequest'
import { Document, UploadFilled } from '@element-plus/icons-vue'

const loading = ref(true)
const updateLoading = ref(false)
const originalData = ref([]) // 存储全量数据
const productTypes = ref([]) // 存储产品型号列表
const selectedProductType = ref('') // 当前选中的型号
const OnlineDialogVisible = ref(false) // 显示在线设备更新对话框
const OfflineDialogVisible = ref(false) //显示离线设备更新对话框
const deviceLoading = ref(false)
const deviceList = ref([])
const DeleteDialogVisible = ref(false)
const EditDialogVisible = ref(false)
const deletingRow = ref(null)
const editingRow = ref(null)
const form = ref({})
const selectedOnlineDevices = ref([]) //选择的在线设备列表
const selectedOfflineDevices = ref([]) //选择的离线设备列表
const onlineDeviceList = ref([]) //所有在线设备
const offlineDeviceList = ref([]) //所有离线设备
const globalUpdateDialogVisible = ref(false) //一键更新弹窗显示状态
const uploadRef = ref(null)
const currentFile = ref({})
const fileList = ref([])
const fileSizeWarning = ref(false)
const selectedVersion = ref(null) // 用于在线设备弹窗
const globalSelectedVersion = ref(null) // 用于全局更新弹窗

const emptyDescription = computed(() =>
  selectedProductType.value
    ? `${selectedProductType.value} 暂无数据`
    : '请先选择产品型号'
)

const versionOptions = computed(() => {
  const versionsSet = new Set()
  const options = []

  if (originalData.value?.length) {
    originalData.value.forEach((item) => {
      const key = `${item.hardwareVersion}_${item.softwareVersion}`

      // 确保有版本数据且不重复
      if (!versionsSet.has(key) && item.hardwareVersion && item.softwareVersion) {
        versionsSet.add(key)

        options.push({
          key,
          display: `v${item.softwareVersion} (硬件v${item.hardwareVersion})`,
          value: {
            hardwareVersion: item.hardwareVersion,
            softwareVersion: item.softwareVersion
          }
        })
      }
    })
  }

  return options
})

// onMounted(async () => {
//   try {
//     await loadProductTypes()
//     if (selectedProductType.value) {
//       await loadOTAList()
//     }
//   } catch (error) {
//     ElMessage.error('加载失败: ' + error.message)
//   }
// })
onMounted(async () => {
  try {
    // 优先尝试从本地存储获取选中的型号
    const savedProductType = localStorage.getItem('selectedProductType')
    if (savedProductType) {
      selectedProductType.value = savedProductType
    }

    await loadProductTypes()
    await loadOTAList()  // 确保加载列表逻辑执行
  } catch (error) {
    ElMessage.error('加载失败: ' + error.message)
  }
})

const formatTime = (timestamp) => {
  return timestamp ? dayjs(timestamp).format('YYYY-MM-DD HH:mm') : '未记录'
}

// 加载产品型号列表
const loadProductTypes = async () => {
  try {
    const res = await getProductType()
    if (res.data?.code === 1) {
      productTypes.value = res.data.data
      if (productTypes.value.length > 0 && !localStorage.getItem('selectedProductType')) {
        selectedProductType.value = productTypes.value[0];
      }
    }
  } catch (error) {
    console.error('型号加载失败:', error)
    ElMessage.warning('型号列表加载失败')
  }
}

const loadOTAList = async () => {
  try {
    loading.value = true
    if (!selectedProductType.value) {
      originalData.value = []
      return
    }
    const res = await getOTAlist(selectedProductType.value)
    if (res.data?.code === 1) {
      originalData.value = res.data.data
    } else {
      originalData.value = []
      ElMessage.warning(res.data?.message || '数据加载异常')
    }
  } catch (error) {
    originalData.value = []
    ElMessage.error('加载失败: ' + error.message)
    console.error('加载错误详情:', error)
  } finally {
    loading.value = false // 无论成功失败都关闭加载状态
  }
}

// 型号切换处理
const handleTypeChange = () => {
  if (selectedProductType.value) {
    localStorage.setItem('selectedProductType', selectedProductType.value);
  } else {
    localStorage.removeItem('selectedProductType');  // 如果清空则移除存储
  }
  loadOTAList()
}

// 一键更新设备
const handleGlobalUpdate = async () => {
  try {
    if (!globalSelectedVersion.value) {
      return ElMessage.warning('请选择固件版本')
    }
    //查看是否有设备
    const res1 = await remoteGetEquipmentNumList(selectedProductType.value)
    if (res1.data.data.length === 0) {
      ElMessage.warning('暂无设备连接')
      return
    }

    updateLoading.value = true
    const res = await updateAllOTA({
      softwareVersion: globalSelectedVersion.value.softwareVersion,
      hardwareVersion: globalSelectedVersion.value.hardwareVersion
    })

    if (res.data?.code === 1) {
      ElMessage.success(res.data.data || '更新指令已发送')
      globalUpdateDialogVisible.value = false
      await loadOTAList()
    } else {
      ElMessage.warning(res.data?.message || '更新操作失败')
    }
  } catch (error) {
    ElMessage.error(
      error.response?.data?.message || error.message || '服务不可用'
    )
  } finally {
    updateLoading.value = false
  }
}

const showOnlineDevices = async () => {
  try {
    await loadDevices()
    // 执行筛选
    onlineDeviceList.value = deviceList.value.filter(
      (d) => d.onlineState === '在线'
    )
    // 重置选择
    selectedVersion.value = null
    selectedOnlineDevices.value = []
    OnlineDialogVisible.value = true
  } catch (error) {
    console.error('加载在线设备失败:', error)
    ElMessage.error('加载在线设备失败，详情请查看控制台')
  }
}

// 显示离线设备对话框
const showOfflineDevices = async () => {
  await loadDevices()
  offlineDeviceList.value = deviceList.value.filter(
    (d) => d.onlineState === '离线'
  )
  OfflineDialogVisible.value = true
}

// 统一加载设备数据
const loadDevices = async () => {
  try {
    deviceLoading.value = true
    const res = await remoteGetEquipmentNumList(selectedProductType.value)
    if (res.data?.code === 1) {
      deviceList.value = res.data.data || []
    }
  } catch (error) {
    // 更详细的错误处理
    console.error('加载设备列表失败:', error)
    let message = '接口请求失败，请检查网络连接'
    if (error.response) {
      message = `服务器错误: ${error.response.status} ${
        error.response.data?.message || ''
      }`
    }
    ElMessage.error(`设备列表加载失败: ${message}`)
  } finally {
    deviceLoading.value = false
  }
}

// 处理离线升级
const handleOfflineUpgrade = async () => {
  try {
    const deviceIds = selectedOfflineDevices.value
    if (!deviceIds.length) {
      return ElMessage.warning('请选择离线设备')
    }

    const res = await updateOfflineOTA(selectedOfflineDevices.value)
    if (res.data?.code === 1) {
      ElMessage.success('离线升级计划已建立')
      OfflineDialogVisible.value = false
      selectedOfflineDevices.value = []
    }
  } catch (error) {
    ElMessage.error(error.message)
  }
}

// 修改handleOnlineUpgrade方法
const handleOnlineUpgrade = async () => {
  try {
    console.log('selectedOnlineDevices:', selectedOnlineDevices.value)
    const equipmentNos = selectedOnlineDevices.value
    if (!equipmentNos.length) {
      return ElMessage.warning('请选择在线设备')
    }

    if (!selectedVersion.value) {
      return ElMessage.warning('请选择固件版本')
    }

    const params = {
      softwareVersion: selectedVersion.value.softwareVersion,
      hardwareVersion: selectedVersion.value.hardwareVersion
    }
    const res = await updateOnlineOTA(equipmentNos, params)

    if (res.data?.code === 1) {
      ElMessage.success('请求已成功发送')
      OnlineDialogVisible.value = false
      selectedVersion.value = null
      selectedOnlineDevices.value = []
    }
  } catch (error) {
    ElMessage.error(
      error.response?.data?.message || error.message || '更新失败'
    )
  }
}

const handleDelete = (row) => {
  deletingRow.value = row // 存储当前操作行
  console.log(row)
  DeleteDialogVisible.value = true
}

// 新增确认方法
const confirmDelete = async () => {
  try {
    if (!deletingRow.value) return

    const res = await DeleteOTA(deletingRow.value.otaId)
    if (res.data?.code === 1) {
      ElMessage.success('删除成功')
      await loadOTAList() // 刷新列表
    }
  } catch (error) {
    ElMessage.error('删除失败')
  } finally {
    DeleteDialogVisible.value = false
    deletingRow.value = null
    await loadProductTypes()
    if (selectedProductType.value) {
      await loadOTAList() 
    }
  }
}

const filterVersionInput = (value) => {
  return value
    .replace(/[^\d.]/g, '') // 移除非数字和点号
    .replace(/\.{2,}/g, '.') // 禁止连续点号
}

const handleEdit = (row) => {
  editingRow.value = row // 将当前行数据填充到表单
  form.value = {
    otaId: row.otaId,
    otaFileName: row.otaFileName,
    productType: row.productType,
    softwareVersion: row.softwareVersion,
    hardwareVersion: row.hardwareVersion,
    createAt: row.createAt
  }
  EditDialogVisible.value = true
}

const confirmEdit = async () => {
  try {
    if (!editingRow.value) return

    const formData = new FormData()
    formData.append('otaId', editingRow.value.otaId.toString())
    formData.append('productType', form.value.productType || '')
    formData.append('softwareVersion', form.value.softwareVersion || '')
    formData.append('hardwareVersion', form.value.hardwareVersion || '')

    if (fileList.value.length > 0 && currentFile.value) {
      // 获取原始文件对象（去除 Vue 的 Proxy 包装）
      const rawFile = currentFile.value.raw || currentFile.value

      // 确保我们得到的是原生 File 对象
      if (rawFile instanceof File) {
        console.log('添加原始文件对象:', rawFile)
        formData.append('OTAFile', rawFile)
      } else {
        console.error('未找到有效文件对象:', rawFile)
        ElMessage.error('文件对象无效')
        return
      }
    } else {
      console.log('没有选择新文件')
    }

    loading.value = true
    const res = await EditOTA(formData)
    if (res.data?.code === 1) {
      ElMessage.success('修改成功')
      await loadOTAList() // 刷新列表
      closeEditDialog()
    }
  } catch (error) {
    ElMessage.error('修改失败: ' + (error.message || '接口错误'))
  } finally {
    loading.value = false
    EditDialogVisible.value = false
    editingRow.value = null
    form.value = {}
    await loadProductTypes()
    if (selectedProductType.value) {
      await loadOTAList()
    }
  }
}

//校验固件输入格式
const isValidSoftwareVersion = computed(() => {
  return /^\d+\.\d+\.\d+$/.test(form.value.softwareVersion || '')
})

//校验硬件输入格式
const isValidHardwareVersion = computed(() => {
  return /^\d+\.\d+$/.test(form.value.hardwareVersion || '')
})

// 显示全局更新弹窗
const showGlobalUpdateDialog = () => {
  globalSelectedVersion.value = null
  globalUpdateDialogVisible.value = true
}
// 文件大小格式化函数
const formatFileSize = (bytes) => {
  if (!bytes || bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 文件变更处理
const handleFileChange = (file, files) => {
  currentFile.value = file
  fileList.value = files

  // 文件大小验证 (500MB)
  fileSizeWarning.value = file.size > 500 * 1024 * 1024
  if (fileSizeWarning.value) {
    ElMessage.warning('文件大小超过500MB，请选择更小的文件')
  }

  return true
}

// 文件移除处理
const handleFileRemove = () => {
  currentFile.value = {}
  fileSizeWarning.value = false
  fileList.value = []
}

// 关闭编辑对话框
const closeEditDialog = () => {
  EditDialogVisible.value = false
  handleFileRemove() // 清除文件选择状态
}
</script>

<style lang="scss" scoped>
.container {
  border-radius: 20px;
  font-weight: bold;
  font-size: 17px;
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;

  /* 调整表格行高 */
  :deep(.el-table__row) {
    height: 48px;
  }

  /* 表头样式 */
  :deep(.el-table__header) {
    th {
      background-color: #f8f9fa;
      color: #333;
      font-weight: bold;
    }
  }

  /* 空数据提示 */
  :deep(.el-table__empty-block) {
    min-height: 300px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  /* 按钮样式（如果未来需要操作列） */
  .el-button--primary {
    background-color: #077aee;
    color: #fff;
    font-weight: bold;
    &:hover {
      background-color: #0669d4;
    }
  }
}
.action-container {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.partially-updated {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}
.version-selection {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 20px;

  .version-item {
    display: flex;
    align-items: center;

    .version-label {
      width: 120px;
      text-align: right;
      margin-right: 10px;
    }

    .el-select {
      flex: 1;
    }
  }
}
</style>
